#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#include <time.h>

#define LOCAL_SOCCKET_NAME "/tmp/local_socket"          //本地套接字路径及文件名

void data_dispose(char *cmd)
{
	if(strncmp(cmd, "localtime", strlen("localtime")) == 0)
    {
		char result[512] = "";
		/*
		char *week_day[] = {
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
		"Saturday",
		};
		*/
		char *week_day[] = {
        "星期日",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
		"星期六",
		};
		time_t time_tmp;
		struct tm *time_now;		
		
		time(&time_tmp);
        time_now = gmtime(&time_tmp);		
		snprintf(result, sizeof(result),
						"%d-%02d-%02d "\
						"%02d:%02d:%02d "\
						"%s", 
						time_now->tm_year+1900,
						time_now->tm_mon+1,
						time_now->tm_mday,
						time_now->tm_hour,
						time_now->tm_min,
						time_now->tm_sec,
						week_day[time_now->tm_wday]);
		printf("%s\n", result);
    }
}

void cgi_dispose(void)
{
	char *method = NULL;
	
	printf("%s\n\n", "content-type:text/html");
	method = getenv("REQUEST_METHOD");
	//get方法获取服务器的内容
	if(strncmp(method, "GET", strlen("GET")) == 0)
	{
		char *content = NULL;
	
		content = getenv("QUERY_STRING");
		//printf("%s", content);
		data_dispose(content);
	}
	//post方法获取服务器的内容
	else if(strncmp(method, "POST", strlen("POST")) == 0)
	{
		char *length = NULL;
		int data_length = 0;
		char *data_container = NULL;
		
		length = getenv("CONTENT_LENGTH");
		data_length = atoi(length);
		data_container = (char *)calloc(1, data_length + 1);
		fgets(data_container, data_length + 1, stdin);
		//printf("%s", data_container);
		data_dispose(data_container);
		free(data_container);
		data_container = NULL;
	}
	fflush(stdout);
}

int main(int argc, char *argv[])
{
	cgi_dispose();
	return 0;
}

